package com.digitalchina.lxnsy.activity.old;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.adapter.CartAdapter;
import com.digitalchina.lxnsy.api.BusinessCart;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.CartVO;
import com.digitalchina.lxnsy.interfaces.ICallBack;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.MathExtend;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：购物车
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2016/12/30 13:48
 * 修改备注：
 * ================================================
 */

public class CartActivity extends BaseActivity implements ICallBack {

    @Bind(R.id.expand_list_view)
    ExpandableListView expandListView;
    @Bind(R.id.swipe_refresh_layout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Bind(R.id.cart_cb_total)
    CheckBox cartCbTotal;
    @Bind(R.id.cart_tv_clear_invalid)
    TextView cartTvClearInvalid;
    @Bind(R.id.cart_tv_clearing)
    TextView cartTvClearing;
    @Bind(R.id.cart_tv_total_price)
    TextView cartTvTotalPrice;
    @Bind(R.id.cart_tv_total)
    TextView cartTvTotal;
    @Bind(R.id.cart_tv_total_tag)
    TextView cartTvTotalTag;
    @Bind(R.id.cart_ll_total)
    LinearLayout cartLlTotal;

    private CartAdapter cartAdapter;

    private List<CartVO> groupList = new ArrayList<>();
    private List<List<CartVO.ShoppingCartItemVOListBean>> childList = new ArrayList<>();
    private int selectNumber = 0;
    boolean isDelete = false;

    @Override
    public void setLayout() {
        setTitle("购物车");
        setRightText("编辑");
        setContentLayout(R.layout.activity_shop_cart);
    }

    @Override
    public void initMember() {

        swipeRefreshLayout.setEnabled(true);

        cartAdapter = new CartAdapter(this, this, groupList, childList);

        expandListView.setAdapter(cartAdapter);
        expandListView.setGroupIndicator(null);
        expandListView.setDividerHeight(2);

        getNetData();
    }

    private void getNetData() {
        BusinessCart.getShoppingCartItems(this, mHandler);
    }


    @Override
    public void addListener() {
        // 父
        expandListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView expandableListView, View view, int i, long l) {
                return true;
            }
        });
        // 子
        expandListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {
                return false;
            }
        });

//        cartCbTotal.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
//                for (int i = 0; i < groupList.size(); i++) {
//                    groupList.get(i).setCheck(isChecked);
//                    for (int j = 0; j < childList.get(i).size(); j++) {
//                        childList.get(i).get(j).setCheck(isChecked);
//                    }
//                }
//                cartAdapter.notifyDataSetChanged();
////                cartTvTotalPrice.setText(getTotal());
//                if (!isDelete) {
//                    cartTvTotalPrice.setText(getTotal());
//                    // 设置总价 物品个数
//                    cartTvClearing.setText(String.format("结算(%s)", String.valueOf(selectNumber)));
//                } else {
//                    getTotal();
//                    cartTvClearing.setText(String.format("删除(%s)", String.valueOf(selectNumber)));
//                }
//            }
//        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getNetData();
            }
        });

//        cartAdapter.setOnAllCheckedBoxNeedChangeListener(new CartAdapter.OnAllCheckedBoxNeedChangeListener() {
//            @Override
//            public void onCheckedBoxNeedChange(boolean allParentIsChecked) {
//                cartCbTotal.setChecked(allParentIsChecked);
//            }
//        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if (null != swipeRefreshLayout)
                    swipeRefreshLayout.setRefreshing(false);

                switch (msg.what) {
                    case MSG.MSG_GET_SHOPPING_CART_ITEMS_SUCCESS:
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_SHOPPING_CART_ITEMS_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_REMOVE_SHOPPING_CART_ITEM_LIST_SUCCESS:
//                        showToast("删除成功");
//                        selectNumber = 0;
//                        cartTvClearing.setText(String.format("删除(%s)", String.valueOf(selectNumber)));
                        removeDeleteItem();
                        cartAdapter.notifyDataSetChanged();
                        break;
                    case MSG.MSG_REMOVE_SHOPPING_CART_ITEM_LIST_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case Constant.DIALOG_DELETE_WHAT:
                        BusinessCart.removeShoppingCartItemList(CartActivity.this, getCheckedItemsID(), mHandler);
                        break;
                    case MSG.MSG_CLEAR_INVALID_ITEMS_SUCCESS:
                        getNetData();
                        break;
                    case MSG.MSG_CLEAR_INVALID_ITEMS_FIELD:
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    /**
     * 移除已经删除的商品项   //TODO 有问题 待优化
     */
    private void removeDeleteItem() {

        List<String> stringList = getCheckedItemsIDList();
        for (int i = 0; i < groupList.size(); i++) { // 父List

            for (int j = 0; j < stringList.size(); j++) { // 选中List
                for (int k = 0; k < childList.get(i).size(); k++) { // 子List
                    if (childList.get(i).get(k).getShoppingCartItemId().equals(stringList.get(j))) {
                        childList.get(i).remove(k);
                        k--;
                    }
                }

            }
        }
        for (int i = 0; i < groupList.size(); i++) {
            if (groupList.get(i).getShoppingCartItemVOList().size() < 1) {
                groupList.remove(i);
                i--;
            }
        }

        setListData(groupList);
    }

    @Override
    public void callBack(Object object) {
        groupList.clear();
        childList.clear();
        groupList = FastJsonUtil.getListBean(object.toString(), "body", "result", CartVO.class);
        if (groupList != null)
            setListData(groupList);
    }

    /**
     * 设置父子list
     *
     * @param groupList
     */
    private void setListData(List<CartVO> groupList) {

        childList.clear();

        for (int i = 0; i < groupList.size(); i++) {
            List<CartVO.ShoppingCartItemVOListBean> shoppingCartItemVOListBeen = groupList.get(i).getShoppingCartItemVOList();
            childList.add(shoppingCartItemVOListBeen);
        }

        cartAdapter.setListData(groupList, childList);

        // 展开所有列表
        for (int i = 0; i < cartAdapter.getGroupCount(); i++)
            expandListView.expandGroup(i);

        cartTvTotalPrice.setText(getTotal());

//        cartTvClearing.setText(String.format("删除(%s)", String.valueOf(selectNumber)));

//        cartCbTotal.setChecked(cartAdapter.dealAllParentIsChecked());

    }

    /**
     * 获取已经选中商品的总价
     *
     * @return 总价
     */
    private String getTotal() {
        String total = "0.00";
        selectNumber = 0;
        for (int i = 0; i < groupList.size(); i++) {
            for (int j = 0; j < childList.get(i).size(); j++) {
                if (childList.get(i).get(j).isCheck()) {
                    total = MathExtend.add(total, MathExtend.multiply(childList.get(i).get(j).getItemPrice(), childList.get(i).get(j).getItemQuantity()));
                    selectNumber++;
                }
            }

        }
        return String.valueOf(total);
    }

    @Override
    public void rightOnClick() {
//      首次点击按钮进入删除物品界面 isDelete初始状态为false
        if (isDelete) {
            // 购买界面状态
            setRightText("编辑");
            isDelete = false;
            cartTvClearInvalid.setVisibility(View.GONE);
            cartLlTotal.setVisibility(View.VISIBLE);
            cartTvTotalPrice.setText(getTotal());
            cartTvClearing.setText(String.format("结算(%s)", String.valueOf(selectNumber)));
            cartTvClearing.setBackgroundResource(R.color.colorFontRed);
        } else {
            // 删除界面状态
            setRightText("完成");
            isDelete = true;
            cartTvClearInvalid.setVisibility(View.VISIBLE);
            cartLlTotal.setVisibility(View.GONE);
            cartTvClearing.setText(String.format("删除(%s)", String.valueOf(selectNumber)));
            cartTvClearing.setBackgroundResource(R.color.app_color);
        }
        cartAdapter.setDelete(isDelete);
        cartAdapter.notifyDataSetChanged();
    }

    @Override
    public void clickOk() {
        if (!isDelete) {
            cartTvTotalPrice.setText(getTotal());
            // 设置总价 物品个数
            cartTvClearing.setText(String.format("结算(%s)", String.valueOf(selectNumber)));
        } else {
            getTotal();
            cartTvClearing.setText(String.format("删除(%s)", String.valueOf(selectNumber)));
        }
    }

    /**
     * 获取已经选中的商品ID
     *
     * @return String
     */
    private String getCheckedItemsID() {
        String checkedItemsID = "";
        for (int i = 0; i < groupList.size(); i++) {
            for (int j = 0; j < childList.get(i).size(); j++) {
                if (childList.get(i).get(j).isCheck())
                    checkedItemsID += (String.format("%s,", childList.get(i).get(j).getShoppingCartItemId()));
            }
        }
        if (checkedItemsID.length() < 1)
            return "";

        return checkedItemsID.substring(0, checkedItemsID.length() - 1);
    }

    /**
     * 获取已经选中的商品ID
     *
     * @return List<String>
     */
    private List<String> getCheckedItemsIDList() {
        List<String> checkedItemsID = new ArrayList<>();
        for (int i = 0; i < groupList.size(); i++) {
            for (int j = 0; j < childList.get(i).size(); j++) {
                if (childList.get(i).get(j).isCheck()) {
                    checkedItemsID.add(childList.get(i).get(j).getShoppingCartItemId());
                }
            }
        }

        return checkedItemsID;
    }

    /**
     * 获取已选中商品对应的商家
     *
     * @return
     */
    private List<String> getCheckedSupplierList() {
        List<String> checkedSupplier = new ArrayList<>();
        for (int i = 0; i < groupList.size(); i++) {
            for (int j = 0; j < childList.get(i).size(); j++) {
                if (childList.get(i).get(j).isCheck()) {
                    // 这个记录的是商家id 后面跳转需要判断 目前不支持多商家结算
                    checkedSupplier.add(groupList.get(i).getSupplierId());
                }
            }
        }

        return checkedSupplier;
    }

    @OnClick({R.id.cart_tv_clear_invalid, R.id.cart_tv_clearing})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cart_tv_clear_invalid:

                clearInvalidItems();

                break;
            case R.id.cart_tv_clearing:
                if (isDelete) {
                    // 删除
                    deleteChecked();
                } else {
                    // 结算
                    closeAnAccount();
                }
                break;
        }
    }

    /**
     * 清空失效的商品（已下架、已作废）
     */
    private void clearInvalidItems() {
        BusinessCart.clearInvalidShoppingCartItems(this, mHandler);
    }

    /**
     * 删除已选中的商品
     */
    private void deleteChecked() {
        if (getCheckedItemsID().length() < 1)
            showToast("未选中任何商品");
        else{
            new MaterialDialog.Builder(this)
                    .title("提示")
                    .content("是否从购物车移除所选商品？")
                    .positiveText("确定")
                    .negativeText("取消")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            BusinessCart.removeShoppingCartItemList(CartActivity.this, getCheckedItemsID(), mHandler);
                        }
                    })
                    .show();
        }
    }

    List<CartVO> listCartVO;

    /**
     * 结算
     */
    private void closeAnAccount() {

        if (getCheckedItemsID().length() < 1) {
            showSnackbar("未选中任何商品");
            return;
        }

        if (!isSingleSupplier()) {
            showSnackbar("目前仅支持单商家结算");
            return;
        }

        listCartVO = getCheckedItems();

        GotoUtil.gotoActivity(CartActivity.this, SubmitOrderActivity.class, "cartList", listCartVO);
    }

    /**
     * 获取已经选中的商品
     *
     * @return
     */
    private List<CartVO> getCheckedItems() {

        List<CartVO> checkedGroupList = new ArrayList<>();

        for (int i = 0; i < groupList.size(); i++) {

            if (getCheckedSupplierList().get(0).equals(groupList.get(i).getSupplierId())) {
                checkedGroupList.add(groupList.get(i));
                break;
            }
        }


        return checkedGroupList;
    }

    /**
     * 选中的商品是否为同一个供应商
     *
     * @return true为一个供应商  false 不同供应商
     */
    private boolean isSingleSupplier() {
        if (getCheckedSupplierList().size() == 0)
            return false;

        for (int i = 0; i < getCheckedSupplierList().size(); i++) {
            if (!getCheckedSupplierList().get(0).equals(getCheckedSupplierList().get(i)))
                return false;
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
